package com.lpj.base.id.generator.autoconfigure;

import com.lpj.base.id.generator.service.impl.provider.MachineIdProvider;
import com.lpj.base.id.generator.service.impl.provider.RedisMachineIdProvider;
import com.robert.vesta.service.intf.IdService;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;

/**
 * @author LiPengJu
 * @date: 2020/4/19
 */
@Configuration
@EnableConfigurationProperties(IdGeneratorProperties.class)
@ConditionalOnClass({RedisTemplate.class})
@ConditionalOnMissingBean({IdService.class})
public class IdGeneratorRedisAutoConfig {
    private final IdGeneratorProperties properties;

    public IdGeneratorRedisAutoConfig(IdGeneratorProperties properties) {
        this.properties = properties;
    }

    @Bean
    @ConditionalOnProperty(prefix = "service.id", name = "machine-id-provider", havingValue = "redis", matchIfMissing = true)
    public IdService idRedisService(RedisTemplate redisTemplate) {
        MachineIdProvider machineIdProvider = RedisMachineIdProvider.getInstance(properties.getMachineIdKey(), redisTemplate);
        return properties.getIdService(machineIdProvider);
    }

}